/* SVN FILE: $Id: settings.js 37 2007-08-26 22:57:19Z killergeorge $ */
/**
 * To quote Dave Cardwell: 
 * Built on the shoulders of giants:
 *   * John Resig      - http://jquery.com/
 *
 * JamalJamal AdobeAir Settings component for JAMAL Javascript MVC Assembly Layout <http://jamal-mvc.com/>
 * Copyright (c)    2007, Georg Leciejewski
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright        Copyright (c) 2007, Georg Leciejewski
 * @link            
 * @package          jamal
 * @subpackage       jamal.setting
 * @since            Jamal v 0.4
 * @version          $Revision: 37 $
 * @modifiedby       $LastChangedBy: killergeorge $
 * @lastmodified     $Date: 2007-08-26 22:57:19 +0000 (Sun, 26 Aug 2007) $
 * @license          http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Jamal AdobeAir Settings component
 *
 * @public
 * @name jamal
 * @cat airSettings
 */
jamal.fn.extend({
    /* Constructor */
	/**
	 * Start the jamal airSettings file handling
	 *
     * @example 
     * @desc 
	 * @public
	 * @name airSettings
	 * @type Object
	 * @cat airSettings
	 */
     airSettings: function () {
	 	
		jamal.log('lkasfjasdldsajdasjlkdsajlk');
		
		if(!jamal.airSettings.stream)
		{//init stream handler		
			jamal.airSettings.stream 	= new air.FileStream();
		}
		
		if(!jamal.airSettings.file)
		{//init settings file handler	 	
        	jamal.airSettings.file = air.File.applicationStorageDirectory;
			jamal.airSettings.file = jamal.airSettings.file.resolve(jamal.airSettings.filename);
		} 	
    }
}); 

jamal.fn.extend(jamal.fn.airSettings, {
	
	/**
	 *  The preferences file
	 */
	file: null,
	
	/**
	 * the preference filename
	 */
	filename: 'preferences.xml',
	
	/**
	 * the filestream
	 */
	stream: null,
	
	/**
	 * how to handle the settings data, default is xml , json should follow soon
	 */
	dataMethod: 'xml',
	    
	/**     
	 *
	 * @example jamal.settings.show();
	 *
	 * @public
	 * @name jamal.airSettings.read
	 * @type Function
	 * @cat message
	 * @param Mixed - String - the filename  / Object - air file object
	 * 
	 * @return string data - the file content
	 */
    read: function() {
		jamal.log('Start Component airSettings read');
		if(this.dataMethod =='xml')
		{//write xml
			return this.readXml();			
		}      
    },
    
    save: function(data) {
		jamal.log('Start Component airSettings save');
		if(this.dataMethod =='xml')
		{//write xml
			this.saveXml(data);			
		}	      
    },    
	
	
	/**
	 * get a single settings value
	 * @param String - the settings name
	 * @return Mixed - the value of the variable, actually the type is nor checked yet
	 * 					boolean false if there are no settings ot the value 
	 */
	get: function (name) {
		jamal.log('Start Component airSettings get');
		var data 	= null;
		var setting = false;
		//read settings
		if(this.dataMethod =='xml')
		{
			data  = this.readXml();
			if(data)
			{//got some data
				for (var i=0; i < data.length; i++ )
				{
					if(name == data[i].name)
					{
						setting = data[i].value;
					}
				}
				if(setting)
				{//got a setting
					return setting;
				}
				else
				{//return default false
					return setting;
				}
			}						
		}
		else
		{
			return false;
		}

	},
	
	/**
	 * apply window settings to the window -> width, height, position
	 */
	applyWindow: function () {
		jamal.log('Start Component airSettings applyWindow');
		//not very nice since this.get opens up a new filestream foreach get .. 		
		window.moveTo(this.get("win_x"), this.get("win_y"));
		window.resizeTo(this.get("win_width"), this.get("win_height"));
	},
	
	/**
	* read the settings from the xml file, return a js array containing th settings as objects
	* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	*/
	readXml: function () {
		jamal.log('Start Component airSettings readXml');
		
		//jamal.log(this.file.nativePath);
		
		var data = [];
		var xml  = null;
		
		if (this.file.exists) 
		{//read data
			this.stream.open(this.file , air.FileMode.READ);			
			xml = this.stream.readUTFBytes(this.stream.bytesAvailable);
			this.stream.close();		
			data = this.xmlToData(xml);		
			return data;
		}
		else
		{//file does not exist yet		
			return false;
		}			
	},	
	
	/**
	 * save new settings into an xml file.
	 * later do: if settings exist they are existing joined new vals are appended
	 *  
	 * @param {Array} data - formated by form pugin formToArrayin the form of 
	 * 						[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	 */
	saveXml: function (data) {
		jamal.log('Start Component airSettings saveXml');
		var xml = this.dataToXml(data);
		//WRITE		
		this.stream.open( this.file, air.FileMode.WRITE );			
		//save data
		this.stream.writeUTFBytes(xml);
		//close stream
		this.stream.close();		
	},	
	
	/**
	 * 
	 * @param {Array} data - formated by form pugin formToArrayin the form of 
	 * 						[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	 */
	dataToXml:function (data) {
		
		jamal.log('Start SettingModel convertToXml');
		var cr = air.File.lineEnding;
		var xml_string = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+cr;
		xml_string +='<settings>'+cr;
		for(var i = 0; i < data.length; i++)
		{
			xml_string +='<setting>' + cr +
							'<name>'+data[i].name+'</name>' + cr +
							'<value>'+data[i].value+'</value>' + cr +
						'</setting>'+cr;
			
		}
		xml_string +='</settings>'+cr;
		return xml_string;
	},
	
	/**
	* parse the xml file contents into a javascript array holding an object for each setting:
	* 	[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	*/
	xmlToData: function (xml)	{
		jamal.log('Start Component airSettings xmlToData');
		var name = "";
		var value = "";
		var data = [];		
		
		var domParser = new DOMParser();
		xml = domParser.parseFromString(xml, "text/xml");
		
		$("settings setting", xml).each( function () {
				name  = $("name", this).text();
				value = $("value", this).text();
				data.push({name:name, value:value});
			});
		
		return data;		
	}		
	
});